/**
 * 试剂列表
 */
import { FC, useEffect, useState } from "react";
import { observer, inject } from "mobx-react";
import { Button, message, Table, Space, Popconfirm, Tooltip } from "antd";
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { ITStore } from "../../store";
import { ITReagent, ITColumns, ITDictValue } from "../../store/interfaces";

type TProp = {
  store: ITStore;
};

const ReagentList: FC<TProp | any> = ({ store }: TProp): JSX.Element => {
  const {
    languageStore: { lang, langCur },
    reagentStore: {
      reagentList,
      getReagentList,
      reagentListLoading,
      delReagentLoading,
      changePage,
      changeSearchList,
      delReagent,
      page,
      totalPage,
      pageSize,
      changeEditingReagentData,
      changeShowAddEditModal,
      searchList,
    },
    dictionaryStore: { getDictValuesByKey },
    userStore: { getUserInfo },
  } = store;

  const [delData, setDelData] = useState<ITReagent | null>(null);

  const [dataSource, setDataSource] = useState<ITReagent[]>([]);

  const [isSearch, setIsSearch] = useState(false);

  const [reagentTypes, setReagentTypes] = useState<ITDictValue[]>([]);

  const [columns, setColumns] = useState<ITColumns[]>([]);

  const pageChange = (nextpage: number) => {
    changePage(nextpage);
    getReagentList();
  };

  const getReagentLabel = (value: string, _langCur: string) => {
    let label = "";
    reagentTypes.some((item) => {
      if (item.value === value) {
        label = item.label;
        if (_langCur === "zhcn") {
          label = item.cnlabel;
        }
        return true;
      }
      return false;
    });
    return label;
  };

  useEffect(() => {
    if (searchList && searchList.length) {
      //   let searchIds: string[] = [];
      //   if (searchList && searchList.length) {
      //     searchList.forEach(({ id }: any) => searchIds.push(id))
      //   }
      //   let tempSearchReagents: ITReagent[] = [];
      //   if (searchIds.length) {
      //     searchIds.forEach((id: string) => {
      //       reagentList.some((item: ITReagent) => {
      //         if (item.id === id) {
      //           tempSearchReagents.push(item)
      //           return true;
      //         }
      //         return false;
      //       })
      //     })
      //   }
      setDataSource(searchList);
      setIsSearch(true);
    } else {
      setDataSource(reagentList);
      setIsSearch(false);
    }
  }, [searchList, reagentList]);

  const modifyItem = (data: ITReagent) => {
    changeEditingReagentData(data);
    changeShowAddEditModal(true);
  };

  const deleteItem = async (data: ITReagent) => {
    setDelData(data);
    const { id } = data;
    const res = await delReagent({ id });
    if (!res) {
      getReagentList();
      message.success(lang["langdeletesuccess"]);
      setDelData(null);
    }
  };

  const defaultColumns: ITColumns[] = [
    {
      title: lang["langname"],
      dataIndex: "name",
      key: "name",
    },
    {
      title: lang["langabbreviation"],
      dataIndex: "abbreviation",
      key: "abbreviation",
    },
    {
      title: lang["langcnname"],
      dataIndex: "cnname",
      key: "cnname",
    },
    {
      title: lang["langformula"],
      dataIndex: "formula",
      key: "formula",
    },
    {
      title: lang["langmolecularweight"],
      dataIndex: "mw",
      key: "mw",
    },
    {
      title: lang["langdensity"],
      dataIndex: "density",
      key: "density",
    },
    {
      title: lang["langpercentage"],
      dataIndex: "percentage",
      key: "percentage",
    },
    {
      title: lang["langstructuralformula"],
      dataIndex: "structural",
      key: "structural",
      render: (url: string) => {
        if (url) {
          return <img src={url} alt="" width="60" />;
        }
        return null;
      },
    },
    {
      title: lang["langcasno"],
      dataIndex: "casno",
      key: "casno",
    },
    {
      title: lang["langmeltingpoint"],
      dataIndex: "mp",
      key: "mp",
    },
    {
      title: lang["langboilingpoint"],
      dataIndex: "bp",
      key: "bp",
    },
    {
      title: lang["langtype"],
      dataIndex: "type",
      key: "type",
      render: (txt: string) => {
        return getReagentLabel(txt, langCur);
      },
    },
    {
      title: lang["langvolatile"],
      dataIndex: "volatile",
      key: "volatile",
      render: (txt: boolean) => {
        return txt ? lang["langyes"] : lang["langno"];
      },
    },
    {
      title: lang["langviscose"],
      dataIndex: "viscose",
      key: "viscose",
      render: (txt: boolean) => {
        return txt ? lang["langyes"] : lang["langno"];
      },
    },
    {
      title: lang["langnote"],
      dataIndex: "note",
      key: "note",
    },
  ];

  const adminColumns: ITColumns[] = [
    {
      title: lang["langedit"],
      dataIndex: "edit",
      key: "edit",
      width: 110,
      align: "center",
      render: (_: string, record: ITReagent) => {
        return (
          <Space>
            <Tooltip title={lang["langedit"]}>
              <Button
                type="link"
                icon={<EditOutlined />}
                onClick={() => {
                  modifyItem(record);
                }}
              />
            </Tooltip>
            <Popconfirm
              title={lang["langconfirmdel"]}
              onConfirm={() => {
                deleteItem(record);
              }}
            >
              <Tooltip title={lang["langdelete"]}>
                <Button
                  type="link"
                  danger
                  loading={delData?.id === record.id && delReagentLoading}
                  icon={<DeleteOutlined />}
                />
              </Tooltip>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    const userInfo = getUserInfo();
    const { privilege } = userInfo || {};
    let tempColumns = [...defaultColumns];
    if (privilege === "admin") {
      tempColumns = [...defaultColumns, ...adminColumns];
    }
    setColumns(tempColumns);
  }, [reagentTypes]);

  useEffect(() => {
    changePage(1);
    changeSearchList(null);
    getReagentList();
    setReagentTypes(getDictValuesByKey("reagentFormType"));

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <Table
      bordered
      loading={reagentListLoading}
      dataSource={dataSource}
      columns={columns}
      pagination={
        isSearch
          ? false
          : {
              current: page,
              pageSize: pageSize,
              onChange: pageChange,
              total: totalPage,
            }
      }
    />
  );
};

export default inject("store")(observer(ReagentList));
